
package com.scsj.supermarket.view.activity.goodmodel;


import android.content.Context;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.google.gson.Gson;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.MainFragmentAdapter;
import com.scsj.supermarket.base.GoodsDetailBase;
import com.scsj.supermarket.base.QueryGoodsDetailEvaluationBase;
import com.scsj.supermarket.bean.GoodsDEvaluationRequestBean;
import com.scsj.supermarket.bean.GoodsDetailEvaluationBean;
import com.scsj.supermarket.bean.QueryGoodsDetailBean;
import com.scsj.supermarket.presenter.GoodsDetailPresenter;
import com.scsj.supermarket.presenter.QueryGoodsDetailEvaluationPresenter;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.utils.Tool;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * 商品详情
 */
public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener,
        GoodsDetailBase.IView,
        QueryGoodsDetailEvaluationBase.IView {
    //顶部轮播图
    private ConvenientBanner mBanner;
    //轮播图右下角数量
    private TextView mTvIndicatorNum;
    //加载图片评论布局
    private LinearLayout reputationImgLayout;

    //底部切换布局相关控件
    private NavigationTabStrip mTopNavigationTabStrip;
    private ViewPager mViewPager;
    private ArrayList<BaseFragment> fragmentList;
    private MainFragmentAdapter mAdpter;
    private String[] title = {"图文相关", "规格参数"};

    private TextView addToCart, moreComment;

    private GoodsDetailPresenter goodsDetailPresenter;
    private QueryGoodsDetailEvaluationPresenter queryGoodsDetailEvaluationPresenter;

    private TextView goodsName;
    private TextView goodsNowPrice;
    private TextView goodsOriginPrice;

    private TextView nickNameTv;
    private TextView timeTv;
    private TextView evaluationContentTv;
    private XLHRatingBar starTv;
    private List<QueryGoodsDetailBean.DataBean.ResourceSecondaryInfoListBean> secondaryInfoListBeans= new ArrayList<>();

    //评价相关集合
    private List<GoodsDetailEvaluationBean.DataBean.AppCommodityEvaluationVoBean.ListBean> evaluationList= new ArrayList<>();
    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_goods_detail);
        initView();
        initData();
        initListener();
    }
    @Override
    protected void initView() {
        queryGoodsDetailEvaluationPresenter= new QueryGoodsDetailEvaluationPresenter(this);
        goodsDetailPresenter= new GoodsDetailPresenter(this);
        goodsName= findViewById(R.id.goods_name);
        goodsNowPrice= findViewById(R.id.goods_detail_original_price_tv);
        goodsOriginPrice= findViewById(R.id.goods_detail_now_price_tv);
        evaluationContentTv= findViewById(R.id.goods_detail_reputation_describe_tv);

        nickNameTv= findViewById(R.id.nick_name);
        starTv= findViewById(R.id.ratingBar);
        timeTv= findViewById(R.id.goods_detail_time_tv);

        /**
         * 顶部轮播图相关
         */
        mBanner = findViewById(R.id.convenient_banner);
        mBanner.setFocusable(true);
        mBanner.setFocusableInTouchMode(true);
        mBanner.requestFocus();
        /**
         * 顶部轮播图相关
         */
        mTvIndicatorNum = findViewById(R.id.tv_indicator_num);
        reputationImgLayout = findViewById(R.id.goods_detail_add_view_tv);
        mTopNavigationTabStrip = findViewById(R.id.mediator_tab);
        mViewPager = findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(2);

        fragmentList = new ArrayList<>();

        fragmentList.add(new GoodsDetailImgTextFragment());
        fragmentList.add(new SpecificationParameterFragment());

        mAdpter = new MainFragmentAdapter(getSupportFragmentManager(), fragmentList);
        mViewPager.setAdapter(mAdpter);
        mViewPager.setCurrentItem(0);

        mTopNavigationTabStrip.setViewPager(mViewPager, 0);
        mTopNavigationTabStrip.setTitles(title);
        mTopNavigationTabStrip.setStripType(NavigationTabStrip.StripType.LINE);
        mTopNavigationTabStrip.setStripGravity(NavigationTabStrip.StripGravity.BOTTOM);
        mTopNavigationTabStrip.setTabIndex(0, true);

        addToCart = findViewById(R.id.goods_detail_add_cart_tv);
        moreComment = findViewById(R.id.goods_detail_more_tv);
    }
    public static List<String> getExample(String str, int num) {
        List<String> bannerList = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            bannerList.add(str + i);
        }
        return bannerList;
    }

    @Override
    protected void initListener() {
        addToCart.setOnClickListener(this);
        moreComment.setOnClickListener(this);
    }

    @Override
    protected void initData() {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("targetType", "shop_goods");
        jsonObject.put("urlTargetExplain", "d8f308a6-74f7-11e8-afb7-70106fb15682");
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        goodsDetailPresenter.deliverData(body);


        GoodsDEvaluationRequestBean evaluationRequestBean= new GoodsDEvaluationRequestBean();
        GoodsDEvaluationRequestBean.GoodsEvaluationDetailBean goodsEvaluationDetailBean= new GoodsDEvaluationRequestBean.GoodsEvaluationDetailBean();
        goodsEvaluationDetailBean.setStoreId("c1b9d0ec-749d-11e8-afb7-70106fb15682");
        goodsEvaluationDetailBean.setGoodsId("5dc87692-74fc-11e8-afb7-70106fb15682");
        evaluationRequestBean.setGoodsEvaluationDetail(goodsEvaluationDetailBean);
        Gson gson = new Gson();
        String obj = gson.toJson(evaluationRequestBean);
        RequestBody body1 = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), obj);
        queryGoodsDetailEvaluationPresenter.deliverData(body1);

    }

    private void addReputationImg(List<String> listImg) {
        if (reputationImgLayout.getChildCount() > 0) {
            reputationImgLayout.removeAllViews();
        }

        for (int i = 0; i < listImg.size(); i++) {

            View view = LayoutInflater.from(this).inflate(R.layout.item_compution_img_layout, null);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    240, 240);
            lp.setMargins(0, 0, Tool.dip2px(this, 10), 10);
            view.setLayoutParams(lp);

            ImageView reputationIv = view.findViewById(R.id.reputation_img);
            Glide
                    .with(this)
                    .load(listImg.get(i))
                    .transform(new Tool.GlideRoundTransform(this, 15))
                    .placeholder(R.mipmap.classify_goods_default)
                    .error(R.mipmap.classify_goods_default)
                    .into(reputationIv);

            reputationImgLayout.addView(view);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back://返回
                finish();
                break;
            case R.id.goods_detail_more_tv://全部评论
                SkipUtils.toAllGoodsCommentPage(this);
                finish();
                break;

            case R.id.goods_detail_add_cart_tv://加入购物车
                finish();
                break;
            default:
                break;
        }
    }

    ////////////////////////////////////////////////轮播图相关////////////////////////////////////////////////

    /**
     * 显示轮播图
     */
    public void showBanner(ConvenientBanner banner, final List<String> listImg, final boolean isShow) {
        int width = Tool.getwindowWidth(this);
        ViewGroup.LayoutParams lp = banner.getLayoutParams();
        lp.height = width;
        lp.width = width;
        banner.setLayoutParams(lp);
        if (listImg.size() > 0) {
            //加载网络图片
            banner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                @Override
                public NetworkImageHolderView createHolder() {
                    if (isShow) {
                        int currentItem = mBanner.getCurrentItem();
                        String source = (currentItem + 1) + "/" + listImg.size();
                        String[] splits = source.split("/");
                        SpannableString spannable = new SpannableString(source);
                        int size = Tool.dip2px(GoodsDetailActivity.this, 12);
                        spannable.setSpan(new AbsoluteSizeSpan(size), 0, splits[0].length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                        mTvIndicatorNum.setText(spannable);
                    }
                    return new NetworkImageHolderView();
                }
            }, listImg).setPointViewVisible(false).startTurning(3000).setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {

                }
            });
        } else {
            //加载本地图片
            if (isShow) mTvIndicatorNum.setText((0) + "/" + 0);
            List<Integer> images = new ArrayList<>();

            images.add(R.mipmap.classify_goods_default);
            mBanner.setPages(new CBViewHolderCreator<LocalImageHolderView>() {
                @Override
                public LocalImageHolderView createHolder() {
                    return new LocalImageHolderView();
                }
            }, images);
        }
    }
    /**
     * 加载网络轮播图图片
     */
    public class NetworkImageHolderView implements Holder<String> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            loadImg(data, imageView);
        }
    }

    /**
     * 轮播图加载本地图片
     */
    private static class LocalImageHolderView implements Holder<Integer> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Integer data) {
            imageView.setImageResource(data);
        }
    }

    /**
     * 显示图片
     */
    private void loadImg(String img, ImageView imageView) {
        if (TextUtils.isEmpty(img))
            Glide.with(this).load(R.mipmap.classify_goods_default).centerCrop().into(imageView);
        else
            Glide.with(this).load(img).placeholder(R.mipmap.classify_goods_default).
                    error(R.mipmap.classify_goods_default).into(imageView);
    }
    ////////////////////////////////////////////////轮播图相关////////////////////////////////////////////////
    @Override
    public void showSuccessMsg(String s, QueryGoodsDetailBean queryGoodsDetailBean) {
        //数据获取成功

        /**
         * 顶部轮播图相关
         */
        secondaryInfoListBeans= queryGoodsDetailBean.getData().getResourceSecondaryInfoList();
        List<String> listImg= new ArrayList<>();
        for (int i=0;i<secondaryInfoListBeans.size();i++){
            //获取轮播图的url
            String imgUrl= secondaryInfoListBeans.get(i).getUrl();
            listImg.add(imgUrl);
        }

        /**
         * 显示顶部轮播图
         */
        showBanner(mBanner, listImg, true);
        /**
         * 商品参数相关
         */
        String goodName= queryGoodsDetailBean.getData().getGoods().getGoodsName();
        double originPrice= queryGoodsDetailBean.getData().getGoods().getGoodsMarketPrice();
        double nowPrice= queryGoodsDetailBean.getData().getGoods().getGoodsPromotionPrice();

        goodsName.setText(goodName);
        goodsNowPrice.setText(String.valueOf(nowPrice));
        goodsOriginPrice.setText(String.valueOf(originPrice));


    }

    @Override
    public void showSuccessMsg(String s, GoodsDetailEvaluationBean goodsDetailEvaluationBean) {

        //查询商品评论成功
        /**
         * 评价相关
         */
        //评价条数
        evaluationList= goodsDetailEvaluationBean.getData().getAppCommodityEvaluationVo().getList();
        //取出来第一条数据进行设置

        //图片评论集合
        List<String> evaluationImgList= new ArrayList<>();

        for (int i=0;i<evaluationList.size();i++){
            //设置昵称
            String nickName= (String) evaluationList.get(0).getNickname();
            nickNameTv.setText(nickName);
            //评论时间
            timeTv.setText(evaluationList.get(0).getGoodsEvaluationDetail().getCreateTime());
            //星星
            starTv.setCountNum(evaluationList.get(0).getGoodsEvaluationDetail().getGevalScoresGoods()/2);

            //评价内容
            String evaluationContent= evaluationList.get(0).getGoodsEvaluationDetail().getGevalContent();
            evaluationContentTv.setText(evaluationContent);

            List list= evaluationList.get(0).getGoodsResourceInfo();
            for (int j=0;j<list.size();j++){
                evaluationImgList.add((String) list.get(j));
            }
        }

        /**
         * 添加評論圖片
         */
        addReputationImg(evaluationImgList);

    }

    @Override
    public void showErrorMsg(String s) {
        Log.e("数据未获取成功",s);

    }

}
